import { Component, Node, Label, Button, _decorator, Vec3, Vec2, input, Input, EventTouch, UITransform } from 'cc';
import { HealthBar } from '../render/TiledObjectData';
import { LOG } from '../../../ConsoleLogCtrl';

const { ccclass, property } = _decorator;

/**
 * 信息提示数据接口
 */
export interface InfoTipData {
    /** 瓦片ID */
    tileId: number;
    /** 血量信息 */
    healthBar?: HealthBar;
    /** 名称 */
    name?: string;
    /** 攻击力 */
    attack?: number;
    /** 位置 */
    position?: { x: number; y: number };
    /** 类型 */
    type?: string;
    /** 攻击范围 */
    attackRange?: number;
    /** 时间戳 */
    timestamp?: number;
    /** 玩家ID */
    playerId?: string;
}

/**
 * 信息提示组件
 * 用于显示实体的详细信息
 */
@ccclass('InfoTip')
export class InfoTip extends Component {

    /** 血量标签 */
    private hpLabel: Label = null;

    /** 名称标签 */
    private nameLabel: Label = null;

    /** 攻击力标签 */
    private attackLabel: Label = null;

    /** 位置标签 */
    private positionLabel: Label = null;

    /** 类型标签 */
    private typeLabel: Label = null;

    /** 攻击范围标签 */
    private rangeLabel: Label = null;

    /** 关闭按钮 */
    private closeButton: Button = null;

    /** 当前显示的数据 */
    private currentData: InfoTipData = null;

    /** 当前关联的TiledObject */
    private currentTiledObject: any = null;

    /** 玩家ID标签 */
    private playerIdLabel: Label = null;

    /** 拖拽相关属性 */
    private isDragging: boolean = false;
    private dragStartPos: Vec2 = new Vec2();
    private nodeStartPos: Vec3 = new Vec3();
    private dragThreshold: number = 10; // 拖拽阈值，超过此距离才认为是拖拽
    private defaultPosition: Vec3 = new Vec3(0, 0, 0); // 默认中心位置

    /**
     * 组件初始化
     */
    protected onLoad(): void {
        this.initializeComponents();
        this.setupEvents();
        this.updateDisplay();
    }

    /**
     * 初始化子组件
     */
    public initializeComponents(): void {
        // 获取各个标签组件
        let infoPanel = this.node.getChildByName('infoPanel');
        this.hpLabel = infoPanel.getChildByName('hp').getComponent(Label);
        this.nameLabel = infoPanel.getChildByName('id').getComponent(Label);
        this.attackLabel = infoPanel.getChildByName('attack').getComponent(Label);
        this.positionLabel = infoPanel.getChildByName('pos').getComponent(Label);
        this.typeLabel = infoPanel.getChildByName('type').getComponent(Label);
        this.rangeLabel = infoPanel.getChildByName('attackRange').getComponent(Label);
        this.playerIdLabel = infoPanel.getChildByName('playerId').getComponent(Label);

        // 获取关闭按钮
        this.closeButton = this.node.getChildByName('closeBtn').getComponent(Button);
    }

    /**
     * 获取子节点组件的辅助方法
     */
    private getChildComponent<T extends Component>(childName: string, componentType: new() => T): T {
        const childNode = this.node.getChildByName(childName);
        if (childNode) {
            return childNode.getComponent(componentType);
        }
        LOG.warn(`InfoTip: 未找到子节点 ${childName}`);
        return null;
    }

    /**
     * 设置事件监听
     */
    private setupEvents(): void {
        if (this.closeButton) {
            this.closeButton.node.on(Button.EventType.CLICK, this.onCloseButtonClick, this);
        }
        
        // 设置拖拽事件监听
        this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
        
        // 修改父节点的鼠标松开事件，只有在非拖拽状态下才关闭
        this.node.getParent().on(Node.EventType.MOUSE_UP, () => {
            if (!this.isDragging) {
                this.node.getParent().active = false;
                this.hide();
            }
        }, this.node.getParent());
    }

    /**
     * 关闭按钮点击事件处理
     * @param event 点击事件
     */
    private onCloseButtonClick(event: any): void {
        // 阻止事件冒泡，防止点击穿透
        if (event && event.propagationStopped !== undefined) {
            event.propagationStopped = true;
        }
        if (event && event.stopPropagation) {
            event.stopPropagation();
        }
        this.hide();
    }

    /**
     * 显示信息提示
     * @param data 要显示的数据
     * @param tiledObject 关联的TiledObject实例
     */
    public show(data: InfoTipData, tiledObject?: any): void {
        this.currentData = data;
        this.currentTiledObject = tiledObject;
        this.updateDisplay();
        if(!this.hpLabel){
            this.initializeComponents();
        }
        
        // 重置位置到默认中心位置
        this.node.setPosition(this.defaultPosition);
        
        this.node.active = true;
        this.node.getParent().active = true;
    }

    /**
     * 隐藏信息提示
     */
    public hide(): void {
        // 通知关联的TiledObject隐藏边框
        if (this.currentTiledObject && this.currentTiledObject.hideSelectionBorder) {
            this.currentTiledObject.hideSelectionBorder();
        }

        this.node.getParent().active = false;
        this.node.active = false;
        this.currentData = null;
        this.currentTiledObject = null;

        // 销毁节点（如果需要的话）
        // if (this.node && this.node.isValid) {
        //     this.node.destroy();
        // }
    }

    /**
     * 更新显示内容
     */
    private updateDisplay(): void {
        if (!this.currentData) {
            return;
        }

        const data = this.currentData;

        // 更新玩家ID
        // if (this.playerIdLabel && data.playerId !== undefined) {
        //     this.playerIdLabel.node.active = true;
        //     this.playerIdLabel.string = `玩家ID: ${data.playerId}`;
        // } 

        // 更新血量信息
        if (this.hpLabel && data.healthBar) {
            this.hpLabel.string = `血量: ${data.healthBar.current}/${data.healthBar.max}`;
        }

        // 更新名称
        if (this.nameLabel && data.name !== undefined) {
            this.nameLabel.string = `名称: ${data.name}`;
        }

        // 根据兵种类型更新攻击力/采集量/建造数/治疗量/生产力
        if (this.attackLabel && data.attack !== undefined) {
            let attackText = '';
            if (data.type === '采集兵') {
                attackText = `采集量: ${data.attack}`;
            } else if (data.type === '建造兵') {
                attackText = `建造数: ${data.attack}`;
            } else if (data.type === '治疗兵') {
                attackText = `治疗量: ${data.attack}`;
            } else if (data.type === '基地') {
                attackText = `生产力: ${data.attack}`;
            } else {
                attackText = `攻击力: ${data.attack}`;
            }
            this.attackLabel.string = attackText;
        }

        // 更新位置
        if (this.positionLabel && data.position) {
            this.positionLabel.string = `位置: ${data.position.x}, ${data.position.y}`;
        }

        // 更新类型
        if (this.typeLabel && data.type !== undefined) {
            this.typeLabel.string = `类型: ${data.type}`;
        }

        // 根据兵种类型更新攻击范围/采集范围/建造范围/治疗范围/生产范围
        if (this.rangeLabel && data.attackRange !== undefined) {
            let rangeText = '';
            if (data.type === '采集兵') {
                rangeText = `采集范围: ${data.attackRange}`;
            } else if (data.type === '建造兵') {
                rangeText = `建造范围: ${data.attackRange}`;
            } else if (data.type === '治疗兵') {
                rangeText = `治疗范围: ${data.attackRange}`;
            } else if (data.type === '基地') {
                rangeText = `生产范围: ${data.attackRange}`;
            } else {
                rangeText = `攻击范围: ${data.attackRange}`;
            }
            this.rangeLabel.string = rangeText;
        }
    }

    /**
     * 更新特定字段的数据
     * @param field 要更新的字段名
     * @param value 新值
     */
    public updateField(field: keyof InfoTipData, value: any): void {
        if (!this.currentData) {
            this.currentData = {} as InfoTipData;
        }

        (this.currentData as any)[field] = value;
        this.updateDisplay();
    }

    /**
     * 获取当前显示的数据
     */
    public getCurrentData(): InfoTipData {
        return this.currentData;
    }

    /**
     * 检查是否正在显示
     */
    public isShowing(): boolean {
        //this.node.getParent().active = false;
        return this.node.getParent().active;
    }

    /**
     * 触摸开始事件处理
     */
    private onTouchStart(event: EventTouch): void {
        this.isDragging = false;
        this.dragStartPos = event.getUILocation();
        this.nodeStartPos = this.node.getPosition();
    }

    /**
     * 触摸移动事件处理
     */
    private onTouchMove(event: EventTouch): void {
        const currentPos = event.getUILocation();
        const deltaPos = currentPos.subtract(this.dragStartPos);
        
        // 检查是否超过拖拽阈值
        if (!this.isDragging && deltaPos.length() > this.dragThreshold) {
            this.isDragging = true;
        }
        
        if (this.isDragging) {
            // 计算新位置
            const newPos = this.nodeStartPos.clone().add(new Vec3(deltaPos.x, deltaPos.y, 0));
            
            // 获取屏幕边界和节点尺寸
            const parentNode = this.node.getParent();
            if (parentNode) {
                const parentSize = parentNode.getComponent(UITransform).contentSize;
                const nodeSize = this.node.getComponent(UITransform).contentSize;
                
                // 计算边界限制
                const halfNodeWidth = nodeSize.width / 2;
                const halfNodeHeight = nodeSize.height / 2;
                const maxX = parentSize.width / 2 - halfNodeWidth;
                const minX = -parentSize.width / 2 + halfNodeWidth;
                const maxY = parentSize.height / 2 - halfNodeHeight;
                const minY = -parentSize.height / 2 + halfNodeHeight;
                
                // 限制位置在边界内
                newPos.x = Math.max(minX, Math.min(maxX, newPos.x));
                newPos.y = Math.max(minY, Math.min(maxY, newPos.y));
            }
            
            this.node.setPosition(newPos);
        }
    }

    /**
     * 触摸结束事件处理
     */
    private onTouchEnd(event: EventTouch): void {
        // 延迟重置拖拽状态，避免立即触发其他点击事件
        this.scheduleOnce(() => {
            this.isDragging = false;
        }, 0.1);
    }

    /**
     * 组件销毁时清理
     */
    protected onDestroy(): void {
        if (this.closeButton) {
            this.closeButton.node.off(Button.EventType.CLICK, this.onCloseButtonClick, this);
        }
        
        // 清理拖拽事件监听
        this.node.off(Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.off(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
        
        this.currentData = null;
    }
}